<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      https://www.dbshop.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   https://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace Admin\Service\Common\PhoneSms;


use Admin\Data\Common;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use Laminas\Json\Json;

class AliSms
{
    private $sendSms;
    private $sendSmsQuery;

    /**
     * 设置短信
     * @param $smsConfig
     * @throws ClientException
     */
    public function setSmsConfig($smsConfig)
    {
        AlibabaCloud::accessKeyClient($smsConfig['sms_id'], $smsConfig['sms_secret'])->regionId('cn-hangzhou')->asDefaultClient();
        $this->sendSms = AlibabaCloud::rpc()->product('Dysmsapi')->version('2017-05-25')->action('SendSms')->method('POST')->host('dysmsapi.aliyuncs.com');
        $this->sendSmsQuery = ['RegionId' => 'cn-hangzhou', 'SignName' => $smsConfig['sms_sign_name']];
    }

    /**
     * 发送短信
     * @param array $data
     * @return bool
     */
    public function sendPhoneSms(array $data)
    {
        try {
            $this->sendSmsQuery = array_merge($this->sendSmsQuery, ['PhoneNumbers' => implode(',', $this->getPhoneNumbers($data['phone'])), 'TemplateCode' => $data['templateCode'], 'TemplateParam' => Json::encode($this->createSmsContent($data['contentArray']))]);
            return $this->sendSms->options(['query' => $this->sendSmsQuery])->request();
        } catch (ClientException $e) {
            echo $e->getErrorMessage() . PHP_EOL;
        } catch (ServerException $e) {
            echo $e->getErrorMessage() . PHP_EOL;
        }
        return false;
    }

    /**
     * 发送订单短信
     * @param array $data
     * @return bool
     */
    public function sendOrderPhoneSms(array $data)
    {
        try {
            $this->sendSmsQuery = array_merge($this->sendSmsQuery, ['PhoneNumbers' => implode(',', $this->getPhoneNumbers($data['phone'])), 'TemplateCode' => $data['templateCode'], 'TemplateParam' => Json::encode($this->createOrderSmsContent($data['contentArray']))]);
            return $this->sendSms->options(['query' => $this->sendSmsQuery])->request();
        } catch (ClientException $e) {
            echo $e->getErrorMessage() . PHP_EOL;
        } catch (ServerException $e) {
            echo $e->getErrorMessage() . PHP_EOL;
        }
        return false;
    }

    /**
     * 获取发送电话号码
     * @param $phoneData
     * @return array
     */
    private function getPhoneNumbers($phoneData)
    {
        $phoneArea      = Common::configValue('list', 'phoneArea');
        $phoneNumbers   = [];
        foreach ($phoneData as $value) {
            if($value['areaCode'] == 'CN') $phoneNumbers[] = $value['number'];
            else $phoneNumbers[] = $phoneArea[$value['areaCode']]['areaPhoneCode'].$value['number'];
        }

        return $phoneNumbers;
    }

    /**
     * 对短信内容进行解析
     * @param $data
     * @return array|string[]
     */
    private function createSmsContent($data)
    {
        $contentArray = [
            'code'  => isset($data['phoneCaptcha']) ? $data['phoneCaptcha'] : '',//手机验证码
        ];

        return array_filter($contentArray);
    }

    /**
     * 对订单提醒的短信内容进行解析
     * @param $data
     * @return array|string[]
     */
    private function createOrderSmsContent($data)
    {
        $contentArray = [
            'buyName'   => isset($data['buyName'])          ? $data['buyName'] : '',    //买家名称,
            'orderSn'   => isset($data['orderSn'])          ? $data['orderSn'] : '',    //订单编号
            'orderTotal'=> isset($data['orderTotal'])       ? $data['orderTotal'] : '', //订单金额
            'deliveryName'  => isset($data['deliveryName'])     ? $data['deliveryName'] : '',   //快递名称
            'expressNumber' => isset($data['expressNumber'])    ? $data['expressNumber'] : '',  //快递单号
        ];

        return array_filter($contentArray);

    }
}